<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <el-form ref="form" :model="queryInfo" label-width="100px">
          <el-row>
            <el-col :span="5">
              <el-form-item label="标签名称：">
                <el-input v-model="queryInfo.tags" placeholder="请输入内容" class="input-head"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="省：" prop="province">
                <el-select v-model="queryInfo.province" placeholder="请选择" class="el-option-head" @change="getCityInfo">
                  <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item" :value="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="市：" prop="city">
                <el-select v-model="queryInfo.city" placeholder="请选择" class="el-option-head">
                  <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="index"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="企业简称：" prop="shortName">
                <el-input v-model="queryInfo.shortName" placeholder="请输入简称" class="input-head"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="状态：" prop="state">
                <el-select v-model="queryInfo.state" placeholder="请选择" class="el-option-head">
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="操作：">
                <el-button type="primary" icon="el-icon-search" @click="searchInfo">搜索</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form>
                <el-button type="primary" icon="el-icon-edit" class="add" @click="addUser">新增用户</el-button>
              </el-form>
            </el-col>
          </el-row>
        </el-form>
        <el-alert type="info" show-icon :closable="false" style="margin-bottom: 10px">共 {{ counts }} 条记录</el-alert>
        <!-- 渲染数据 -->
        <el-table stripe style="width: 100%" v-loading="loading" :data="companyTableDate">
          <el-table-column prop="id" label="序号" width="100px"> </el-table-column>
          <el-table-column prop="number" label="企业编号"> </el-table-column>
          <el-table-column prop="shortName" label="企业简称"> </el-table-column>
          <el-table-column prop="tags" label="标签"> </el-table-column>
          <el-table-column prop="creatorID" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期" :formatter="formateDate"> </el-table-column>
          <el-table-column prop="remarks" label="备注"> </el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              {{ scope.row.state === 1 ? '启用' : '禁用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
              <!-- 启用按钮 -->
              <el-button type="primary" icon="el-icon-setting" size="mini" @click="changeStatus(scope.row)">{{ scope.row.state === 1 ? '启用' : '禁用' }}</el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCompany(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页栏 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts"
          >
          </el-pagination>
        </div>
      </el-card>
      <!-- 新增用户对话框 -->
      <el-dialog title="创建用户" :visible.sync="addDialogVisible" width="50%" @close="closeAdd">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px" style="width: 80%; margin-left: 10px">
          <el-form-item label="企业名称" prop="shortName">
            <el-input v-model="addForm.shortName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="所属公司" prop="company">
            <el-input v-model="addForm.company" autocomplete="off"></el-input>
            <p>https://www.tianyancha.com（在此可查询所属公司全称及简称</p>
          </el-form-item>
          <el-form-item label="城市" prop="province">
            <el-select v-model="addForm.province" placeholder="请选择省份" style="width: 40%; margin-right: 10px" @change="addCityInfo">
              <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item" :value="index"></el-option>
            </el-select>
            <el-select v-model="addForm.city" placeholder="请选择城市" style="width: 40%" @change="getAreaInfo">
              <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向(企业标签)" prop="tags">
            <el-input v-model="addForm.tags" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="addForm.remarks" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCompany">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog title="创建用户" :visible.sync="editDialogVisible" width="50%" @close="closeEdit">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="120px" style="width: 80%; margin-left: 10px">
          <el-form-item label="企业名称" prop="shortName">
            <el-input v-model="editForm.shortName" autocomplete="off"></el-input>
          </el-form-item>
            <el-form-item prop="isFamous" label="是否为名企">
              <el-checkbox v-model="editForm.isFamous"></el-checkbox>
          </el-form-item>
          <el-form-item label="所属公司" prop="company">
            <el-input v-model="editForm.company" autocomplete="off"></el-input>
            <p>https://www.tianyancha.com（在此可查询所属公司全称及简称</p>
          </el-form-item>
          <el-form-item label="城市" prop="province">
            <el-select v-model="editForm.province" placeholder="请选择省份" style="width: 40%; margin-right: 10px" @change="addCityInfo">
              <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item" :value="index"></el-option>
            </el-select>
            <el-select v-model="editForm.city" placeholder="请选择城市" style="width: 40%" @change="getAreaInfo">
              <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向(企业标签)" prop="tags">
            <el-input v-model="editForm.tags" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="editForm.remarks" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCompany">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list as comList, add as comAdd, update as comUpdate, remove as comRemove, disabled as comDisabled } from '@/api/hmmm/companys.js'

// 导入城市函数
import { provinces, citys } from '@/api/hmmm/citys.js'

export default {

  name: 'CompanysList',
  data () {
    return {
      loading: true,
      // 请求参数
      queryInfo: {
        // 当前页码
        page: 1,
        // 每页多少
        pagesize: 5,
        tags: '',
        province: '',
        city: '',
        shortName: '',
        state: null
      },
      counts: 0,
      input: '',
      // 表格
      companyTableDate: [],
      // 省数据
      provinceOptions: [],
      // 市数据
      cityOptions: [],
      // 控制新建用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户的数据绑定
      addForm: {
        isFamous: true,
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: ''
      },
      // 添加表单验证
      addFormRules: {
        shortName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        province: [{ required: true, message: '请输入城市地区', trigger: 'blur' }],
        tags: [{ required: true, message: '请输入企业方向', trigger: 'blur' }]
      },
      // 编辑用户的数据绑定
      editForm: {
        // id: '',
        // number: '',
        // 是否为名企
        isFamous: '',
        shortName: '',
        company: '',
        province: '',
        city: '',
        tags: '',
        remarks: ''
      }
    }
  },
  created () {
    // 获取企业权限列表
    this.getCompanysList()
    // 获取省
    this.getProvinceList()
  },
  methods: {
    /* 格式化日期 */
    formateDate (row, column, val, index) {
      var y = val.substr(0, 4)
      var m = val.substr(5, 2)
      var s = val.substr(8, 2)
      var hh = val.substr(11, 2)
      var mm = val.substr(14, 2)
      var ss = val.substr(17, 2)
      return `${y}-${m}-${s} ${hh}:${mm}:${ss}`
    },
    // -----------------------------------列表渲染-------------------------------------
    // 获取企业管理列表
    async getCompanysList () {
      try {
        const { data: res } = await comList(this.queryInfo)
        this.companyTableDate = res.items
        console.log(this.companyTableDate)
        this.counts = res.counts
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCompanysList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (page) {
      this.queryInfo.page = page
      this.getCompanysList()
    },
    // 获取省
    getProvinceList () {
      this.provinceOptions = provinces()
    },
    // 获取市
    getCityInfo (val) {
      const city = this.provinceOptions[this.queryInfo.province]
      this.cityOptions = citys(city)
      // console.log(this.cityOptions)
      this.queryInfo.city = this.cityOptions[0]
    },
    // 点击搜索
    searchInfo () {
      this.getCompanysList()
    },
    // -----------------------------------添加用户--------------------------------
    // 弹出添加用户对话框
    addUser () {
      this.addDialogVisible = true
      this.cityOptions = []
      this.addForm.city = ''
    },
    // 城市change
    addCityInfo () {
      const province = this.provinceOptions[this.addForm.province]
      // console.log(province)
      this.cityOptions = citys(province)
      // console.log(this.cityOptions)
      this.addForm.province = province
      // console.log(this.addForm.province)
      this.addForm.city = this.cityOptions[0]
      console.log(this.addForm.city)
    },
    // 地区change
    getAreaInfo () {
      this.addForm.city = this.cityOptions[this.addForm.city]
    },
    // 对话框关闭
    closeAdd () {
      this.$refs.addFormRef.resetFields()
      // this.addForm.city = ''
    },
    // 点击确定，提交
    addCompany () {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return false
        try {
          const { data: res } = await comAdd(this.addForm)
          console.log(res)
          this.getCompanysList()
          this.$message.success('添加成功')
        } catch (error) {
          this.$message.error('添加失败')
        }
        this.addDialogVisible = false
      })
    },
    // --------------------------------编辑用户---------------------------------
    // 渲染对话框
    showEditDialog (row) {
      // console.log(row)
      row.isFamous = row.isFamous === 1 ? Boolean(1) : Boolean(0)
      this.editForm = row
      // console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 对话框关闭
    closeEdit () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮，提交
    editCompany () {
      // console.log(this.$refs)
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        try {
          const { data: res } = await comUpdate(this.editForm)
          console.log(res)
          this.getCompanysList()
          this.$message.success('编辑成功')
        } catch (error) {
          this.$message.error('编辑失败')
        }
        this.editDialogVisible = false
      })
    },
    // --------------------------------删除用户----------------------------------
    deleteCompany (row) {
      this.$confirm('此操作将永久删除该公司，是否继续？', '提示', {
        confirmButtonText: '确定',
        canceButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await comRemove(row)
          console.log(res)
          this.$message({ type: 'success', message: '删除成功' })
          this.getCompanysList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // --------------------------------修改状态----------------------------------
    changeStatus (data) {
      this.$confirm('确定切换状态？', '提示', {
        confirmButtonText: '确定',
        canceButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await comDisabled(data)
          this.$message.success(`已成功${data.state === 1 ? '禁用' : '启用'}`)
          this.getCompanysList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消切换'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.input-head {
  width: 150px;
}
.el-option-head {
  width: 100px;
}
.add {
  margin: 15px 0;
  float: right;
}
</style>
